package com.obixlabs.kalua.datacache;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

import com.google.common.collect.Sets;
import com.hazelcast.core.MapLoader;
import com.kalua.list.dbaccess.SimpleCRUDDAO;
import com.kalua.list.domainmodel.Identifiable;
import com.kalua.list.domainmodel.Identifier;

public 	class DatabaseMapLoader<K extends Identifier, V extends Identifiable<K>> 
			implements MapLoader<K, V> {

	private SimpleCRUDDAO<V, K> dbAccessObject;
	private boolean operateAsLazy;
	
	public DatabaseMapLoader(SimpleCRUDDAO<V, K> dataAccessObject) { 
		setDbAccessObject(dataAccessObject); 
		setOperateAsLazy(true);
	}
	
	@Override
	public V load(K key) { return this.dbAccessObject.read(key); }

	@Override
	public Map<K, V> loadAll(Collection<K> keys) 
	{ return this.dbAccessObject.readAll(keys);}

	@Override
	public Set<K> loadAllKeys() {
		Set<K> result;
		if (!isOperateAsLazy()) {
			Map<K, V> allEntries = this.dbAccessObject.readAll();
			result = allEntries.keySet();
		} else result = Sets.newHashSet();		
		return result;
	}
	
	public SimpleCRUDDAO<V, K> getDbAccessObject() { return this.dbAccessObject; }
	private void setDbAccessObject(SimpleCRUDDAO<V, K> dataAccessObject) 
	{ this.dbAccessObject = dataAccessObject; }
	
	public boolean isOperateAsLazy() { return this.operateAsLazy; }
	public void setOperateAsLazy(boolean operateAsLazy) 
	{ this.operateAsLazy = operateAsLazy; }
}